package com.kujie.websocket.controller;

import cn.hutool.core.collection.CollUtil;
import com.kujie.websocket.holder.WebSocketSessionHolder;
import com.kujie.websocket.utils.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @package: com.kujie.websocket.controller
 * @author: 宁在春 公众号【宁在春】
 * @date: 2025-01-16  21:46
 * @desc: WebsocketController
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/websocket")
public class WebsocketController {

    @GetMapping("/push")
    public String push(){
        WebSocketUtils.publishAll("11111");
        return "successful";
    }

    @GetMapping("/sub")
    public String sub(){
        WebSocketUtils.subscribeMessage((message) -> {
            log.info("WebSocket主题订阅收到消息session keys={} message={}", message.getSessionKeys(), message.getMessage());
            // 如果key不为空就按照key发消息 如果为空就群发
            if (CollUtil.isNotEmpty(message.getSessionKeys())) {
                message.getSessionKeys().forEach(key -> {
                    if (WebSocketSessionHolder.existSession(key)) {
                        WebSocketUtils.sendMessage(key, message.getMessage());
                    }
                });
            } else {
                WebSocketSessionHolder.getSessionsAll().forEach(key -> {
                    WebSocketUtils.sendMessage(key, message.getMessage());
                });
            }
        });
        return "11111111111";
    }
}
